<script setup lang="ts">
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import {
  checkUserName,
  checkName,
  checkPhone,
  validID,
} from "@/utils/formValidate";
import request from "@/utils/request.ts";
import API from "@/api";

defineOptions({
  name: "AddMember",
});

let addMemberVisible = ref(false);
let actionType = ref("add");

const openAddMember = (rowInfo: RuleForm | string) => {
  if (typeof rowInfo === "string") {
    actionType.value = "add";
  } else {
    form = rowInfo;
    actionType.value = "edit";
  }
  addMemberVisible.value = true;
};

const titleName = computed(() => {
  return actionType.value === "add" ? "新增员工" : "编辑员工";
});

defineExpose({
  openAddMember,
});

interface RuleForm {
  name: string;
  phone: string;
  sex: string;
  idNumber: string;
  username: string;
  id?: string;
  createUser?: string;
}

const formSize = ref<ComponentSize>("default");
const formRef = ref<FormInstance>();
let form = reactive<RuleForm>({
  name: "",
  phone: "",
  sex: "1",
  idNumber: "",
  username: "",
});

const rules = reactive<FormRules<RuleForm>>({
  username: [
    {
      required: true,
      validator: checkUserName,
      trigger: "blur",
    },
  ],
  //姓名
  name: [{ required: true, validator: checkName, trigger: "blur" }],
  phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
  idNumber: [{ required: true, validator: validID, trigger: "blur" }],
});

const emits = defineEmits(["refresh"]);

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("你确定要关闭吗?").then(() => {
    onClose();
    done();
  });
};

const resetForm = () => {
  formRef.value?.resetFields();
  form = reactive<RuleForm>({
    name: "",
    phone: "",
    sex: "1",
    idNumber: "",
    username: "",
  });
};

const onClose = () => {
  addMemberVisible.value = false;
  resetForm();
};

const submitForm = (formEl: FormInstance | undefined, isContinue: boolean) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (actionType.value === "add") {
        request
          .post(API.saveEmployee, form)
          .then((res) => {
            if (res.code === 1) {
              ElMessage.success("员工添加成功!");
              if (isContinue) {
                resetForm();
                emits("refresh");
              } else {
                emits("refresh");
                onClose();
              }
            }
          })
          .catch((err) => {
            ElMessage.error(err.message);
          });
      } else {
        request.put(API.editEmployee, form).then((res) => {
          if (res.code === 1) {
            ElMessage.success("员工修改成功!");
            onClose();
            emits("refresh");
          }
        });
      }
    } else {
      ElMessage.success("提交失败!");
    }
  });
};
</script>

<template>
  <el-dialog
    :model-value="addMemberVisible"
    :title="titleName"
    width="600"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      :size="formSize"
      status-icon
    >
      <el-form-item label="账号:" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入账号"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="员工姓名:" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入员工姓名"
          maxlength="20"
        />
      </el-form-item>

      <el-form-item label="手机号:" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入手机号"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="性别:" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio label="男" value="1"></el-radio>
          <el-radio label="女" value="0"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号:" prop="idNumber">
        <el-input
          v-model="form.idNumber"
          placeholder="请输入身份证号"
          maxlength="20"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="success" @click="submitForm(formRef, false)">
          保存
        </el-button>
        <el-button
          type="success"
          @click="submitForm(formRef, true)"
          v-if="actionType === 'add'"
        >
          保存并继续添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
